<template>
  <el-drawer
      :title="mangaName + ' 章节列表'"
      size="1000px"
      direction="ltr"
      :append-to-body="true"
      :visible.sync="visible"
      :show-close="false"
      :before-close="handleClose">
    <div id="drawer-main-box">
      <div class="table-top">
        <span style="width: 50px;">
          <el-popover
              width="200"
              trigger="click"
              placement="right">
            <span style="display: flex">
              <el-tooltip class="item" effect="dark" content="※ 默认使用最新章节数填充" placement="top-start">
                <el-input style="width: 120px;" v-model="epForm.name" placeholder="请输入章节名" maxlength="20"/>
              </el-tooltip>
              <el-button class="theme-button" style="margin-left: auto" :loading="submitLoading" type="primary"
                         size="mini" icon="el-icon-check" @click="createEp"/>
            </span>
            <el-button slot="reference" size="small" class="theme-button" type="primary">快速新增</el-button>
          </el-popover>
        </span>
        <span style="width: 200px;">
        <el-input
            clearable
            v-model="keyword"
            placeholder="请输入章节数或章节名">
        </el-input>
        </span>
      </div>

      <manga-ep-page-drawer @flashData="flashData" ref="epPageTable"/>

      <el-dialog
          title="Tips"
          :visible.sync="autoMarkNoticeVisible"
          width="460px"
          append-to-body
          center>
        <div style="display: flex; flex-direction: column;">
          <h4>一键标图功能还处于beta阶段，请酌情使用</h4><br/>
          <table>
            <tr>
              <td>1.</td>
              <td>标记的位置并不一定准确，存在一定误判.</td>
            </tr>
            <tr>
              <td>2.</td>
              <td>由于接入的第三方程序问题，可能会出现翻译内容与标记位置不匹配的情况，此时的标记位置是正确的，只是翻译结果错位了.</td>
            </tr>
            <tr>
              <td>3.</td>
              <td>拖动标记校准位置后，不妨点击右上角的“校准标记”，您的数据提供可以让程序更准确.</td>
            </tr>
          </table>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="autoMarkNoticeVisible = false">取 消</el-button>
          <el-button type="primary" @click="applyMark(focusEpId)">确 定</el-button>
        </div>
      </el-dialog>

      <el-dialog
          title="Tips"
          :visible.sync="autoCutoutNoticeVisible"
          width="460px"
          append-to-body
          center>
        <div style="display: flex; flex-direction: column;">
          <h4>制作大白框功能还处于beta阶段，由于无法控制抠除的文字范围，可能会出现多抠的情况，请酌情使用</h4>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="autoCutoutNoticeVisible = false">取 消</el-button>
          <el-button type="primary" @click="applyCutout(focusEpId)">确 定</el-button>
        </div>
      </el-dialog>

      <!--   表格   -->
      <div id="table-box">
        <template>
          <el-table
              height="calc(100vh - 180px)"
              v-loading="loading"
              :data="filterData"
              stripe
              max-height="calc(100vh - 180px)"
              style="width: 100%">
            <el-table-column
                prop="number"
                label="章节数"
                width="100px"
                align="center"
                sortable>
            </el-table-column>
            <el-table-column
                prop="name"
                label="章节名"
                align="center"
                show-overflow-tooltip
                width="100px">
              <template slot-scope="scope">
                <el-input
                    class="name-edit-box"
                    v-if="scope.row.isEditing"
                    v-model="editText"
                    :ref="scope.$index"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.$index)"
                    @blur="handleInputConfirm(scope.$index)"/>
                <span v-else style="cursor: pointer" @click="showInput(scope.$index)">
                  {{ scope.row.name }} <i style="color: #3c8dbc" class="el-icon-edit"/>
                </span>
              </template>
            </el-table-column>
            <el-table-column
                prop="isAvailable"
                label="烹饪状态"
                width="180px"
                align="center">
              <template slot-scope="scope">
                <el-switch
                    @change="changeStatus(scope.row)"
                    v-model="scope.row.isAvailable"
                    active-color="#409eff"
                    inactive-color="#13ce66"
                    active-text="熟肉"
                    inactive-text="生肉">
                </el-switch>
              </template>
            </el-table-column>
            <el-table-column
                prop="markStatus"
                label="AI标记状态"
                align="center">
            </el-table-column>
            <el-table-column
                prop="cutoutStatus"
                label="AI抠图状态"
                align="center">
            </el-table-column>
            <el-table-column
                prop="sort"
                align="center"
                label="升降序"
                width="100px">
              <template slot-scope="scope">
                <el-button icon="el-icon-caret-top" size="mini" @click="bubbling(scope.row.epId)" circle/>
                <el-button icon="el-icon-caret-bottom" size="mini" @click="bubbling(scope.row.epId, 'down')" circle/>
              </template>
            </el-table-column>
            <el-table-column
                label="操作"
                align="center"
                width="260px">
              <template slot-scope="scope">
                <el-button type="text" size="small" @click="openAutoMarkNotice(scope.row.epId)">一键标图</el-button>
                <el-button type="text" size="small" @click="openAutoCutoutNotice(scope.row.epId)">制作大白框</el-button>
                <el-button type="text" size="small" @click="openPageWindow('raw', scope.row)">生肉</el-button>
                <el-button type="text" size="small" @click="openPageWindow('cooked', scope.row)">熟肉</el-button>
                <el-button style="color: #F56C6C;" @click="deleteEp(scope.row)" type="text" size="small">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </div>
    </div>
  </el-drawer>
</template>

<script>
import {nocacheEpList} from "@/api/mgApi";
import {deepClone} from "@/util/objUtil";
import {createEp, epAvailable, epDeleted, rename, reSort} from "@/api/mgEpApi";
import MangaEpPageDrawer from "@/components/manga/mangaEpPageTable.vue";
import {cutoutApply, markApply} from "@/api/mgTaskApi";

export default {
  name: "mangaEpTable",
  components: {MangaEpPageDrawer},
  data() {
    return {
      visible: false,
      loading: false,
      drag: false,
      isReSort: false,
      submitLoading: false,
      autoMarkNoticeVisible: false,
      autoCutoutNoticeVisible: false,
      keyword: '',
      mangaName: '',
      editText: '',
      currentEditIndex: -1,
      tableData: [],
      focusEpId: null,

      // 表单数据
      epForm: {
        mangaId: 0,
        name: ''
      },
      // 校验规则
      epFormRules: {
        name: [
          {min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur'}
        ]
      },
    }
  },
  computed: {
    // 计算过滤后的数据
    filterData() {
      // 如果关键字为空，则返回全部数据
      if (!this.keyword) return this.tableData
      return this.tableData.filter(item => {
        return item.number.toString().includes(this.keyword) || item.name.includes(this.keyword)
      })
    }
  },
  methods: {
    markApply,
    openWindow(mangaId, name) {
      this.visible = true
      this.mangaName = name
      this.flashData(mangaId)
    },
    async handleClose() {
      // 重排序
      await this.reSort();
      this.visible = false
      this.tableData = []
      this.epForm = {
        mangaId: 0,
        name: ''
      }
      this.$emit('flashTable')
    },
    /**
     * 新增章节
     */
    createEp() {
      this.submitLoading = true
      createEp(this.epForm).then(res => {
        if (res.code === '200') {
          this.$message({
            message: '新增成功',
            type: 'success'
          })
          this.flashData(this.epForm.mangaId)
        }
      }).finally(() => {
        this.submitLoading = false
      })
    },
    deleteEp(row) {
      this.$confirm('确认删除该章节？', {
        type: 'warning',
      }).then(() => {
        let data = {
          epId: row.epId,
          mangaId: this.epForm.mangaId
        }
        epDeleted(data).then(res => {
          if (res.code === '200') {
            this.$message({
              message: '删除成功',
              type: 'success'
            })
            this.flashData(this.epForm.mangaId)
          }
        })
      })
    },
    /**
     * 打开自动标注提示窗口
     * @param epId 章节id
     */
    openAutoMarkNotice(epId) {
      this.autoMarkNoticeVisible = true
      this.focusEpId = epId
    },
    /**
     * 打开自动抠图提示窗口
     * @param epId 章节id
     */
    openAutoCutoutNotice(epId) {
      this.autoCutoutNoticeVisible = true
      this.focusEpId = epId
    },
    /**
     * 申请标记
     */
    applyMark(epId) {
      if (!epId) return
      markApply(epId).then((res) => {
        if (res.code === '200') {
          this.$message({
            message: '任务提交',
            type: 'success'
          })
          this.flashData(this.epForm.mangaId)
        }
      }).finally(() => {this.autoMarkNoticeVisible = false})
    },
    /**
     * 申请抠图
     */
    applyCutout(epId) {
      if (!epId) return
      cutoutApply(epId).then((res) => {
        if (res.code === '200') {
          this.$message({
            message: '任务提交',
            type: 'success'
          })
          this.flashData(this.epForm.mangaId)
        }
      }).finally(() => {this.autoCutoutNoticeVisible = false})
    },
    /**
     * 打开页码管理窗口
     * @param type 类型
     * @param row 行数据
     */
    openPageWindow(type, row) {
      let data = {
        ...row,
        mangaId: this.epForm.mangaId
      }
      this.$refs.epPageTable.openWindow(type, data)
    },
    /**
     * 显示输入框
     * @param index 索引
     */
    showInput(index) {
      let cloneData = deepClone(this.tableData);
      // 如果当前编辑索引不是初始值，则将展示的元素的编辑框展示状态置为false
      if (this.currentEditIndex !== -1) {
        cloneData[this.currentEditIndex].isEditing = false;
      }
      // 显示输入框
      cloneData[index].isEditing = true;
      // 将当前编辑索引置为当前展示的
      this.currentEditIndex = index;
      // 赋值输入框
      this.editText = cloneData[index].name;
      // 刷新列表数据
      this.tableData = cloneData;

      // 聚焦
      this.$nextTick(() => {
        this.$refs[index].$refs.input.focus();
      });
    },
    /**
     * 输入框确认
     * @param index 索引
     */
    handleInputConfirm(index) {
      // 判空
      if (!this.editText) return;
      // 修改章节名
      let cloneData = deepClone(this.tableData);
      // 隐藏输入框
      cloneData[index].isEditing = false;
      // 判断是否一样
      if (this.editText === this.tableData[index].name) {
        this.tableData = cloneData
        this.initEditInput()
        return
      }
      // 更新章节名称
      let data = {
        mangaId: this.epForm.mangaId,
        epId: cloneData[index].epId,
        name: this.editText
      }
      rename(data).then(res => {
        if (res.code === '200') {
          // 刷新列表数据
          this.flashData(this.epForm.mangaId)
        }
      }).finally(() => {
        this.initEditInput()
      })
    },
    initEditInput() {
      this.editText = ''
      this.currentEditIndex = -1
    },
    /**
     * 重排序
     * @returns {Promise<void>}
     */
    async reSort() {
      if (this.isReSort) {
        // 组装请求数据
        let sortList = []
        this.tableData.forEach((item, index) => {
          sortList.push({
            epId: item.epId,
            number: index + 1
          })
        })
        let data = {
          mangaId: this.epForm.mangaId,
          sortList: sortList
        }
        // 重排序
        await reSort(data)
      }
    },
    /**
     * 改变状态
     * @param row 行数据
     */
    changeStatus(row) {
      // 取反还原状态，防止真正修改前icon状态就变化
      row.isAvailable = !row.isAvailable
      this.$confirm('是否要改变烹饪状态?')
          .then(() => {
            let data = {
              mangaId: this.epForm.mangaId,
              epId: row.epId,
              // 因为前面取反还原展示状态了，所以传反的
              isAvailable: !row.isAvailable
            }
            epAvailable(data).then(res => {
              if (res.code === '200') {
                this.$message({
                  message: '操作成功',
                  type: 'success'
                })
                this.flashData(this.epForm.mangaId)
              }
            })
          })
    },
    /**
     * 刷新列表数据
     * @param mangaId 漫画id
     */
    flashData(mangaId) {
      this.loading = true
      this.epForm.mangaId = mangaId
      nocacheEpList(mangaId).then(res => {
        this.tableData = res.data
        this.tableData.forEach((item) => {
          // 控制编辑框显隐
          item.isEditing = false
        })
        this.loading = false
        this.epForm.name = '第 ' + this.getNextNumber() + ' 话'
      })
    },
    /**
     * 获取下一个章节数
     * @returns {*|number}
     */
    getNextNumber() {
      if (!this.tableData || this.tableData.length === 0) return 1
      // 返回列表中最大的章节数加一
      return this.tableData[this.tableData.length - 1].number + 1
    },
    /**
     * 向上或向下冒牌
     * @param epId key
     * @param direction up/down
     */
    bubbling(epId, direction = 'up') {
      this.isReSort = true
      // 深拷贝一份
      let dataClone = deepClone(this.tableData);
      // 获取当前epId的元素
      let currentIndex = dataClone.findIndex(item => item.epId === epId);
      if (currentIndex === -1) return
      // 获取当前元素
      let temp = dataClone[currentIndex];

      // 根据方向调整number
      if (direction === 'up') {
        if (currentIndex > 0) {
          // 交换位置
          dataClone[currentIndex] = dataClone[currentIndex - 1];
          dataClone[currentIndex - 1] = temp;
        }
      } else {
        if (currentIndex < dataClone.length - 1) {
          // 交换位置
          dataClone[currentIndex] = dataClone[currentIndex + 1];
          dataClone[currentIndex + 1] = temp;
        }
      }
      // 更新数据
      this.tableData = dataClone;
    }
  }
}
</script>

<style scoped lang="scss">
#drawer-main-box {
  width: 100%;
  height: 100%;
  padding: 0 20px 0 20px;
  display: flex;
  flex-direction: column;
  justify-items: flex-start;

  .table-top {
    display: flex;
    width: 100%;
    align-items: center;
    justify-content: space-between;
  }

  ::v-deep .el-table__body-wrapper {
    /* 滚动条背景 */
    &::-webkit-scrollbar {
      width: 7px !important;
      height: 7px !important;
      border-radius: 5px !important;
      background-color: rgb(245, 245, 245, 0.5) !important;
    }

    /* 滑块 */
    &::-webkit-scrollbar-thumb {
      border-radius: 5px !important;
      background-color: var(--theme-color) !important;
    }
  }
}

#table-box {
  margin-top: 10px;
  background-color: #f0f0f0; /* 设置背景色 */
  border-top: 1px solid #ccc; /* 仅保留上边框 */
  border-bottom: 1px solid #ccc; /* 仅保留下边框 */
  border-radius: 5px; /* 保持圆角 */
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2), 0 -2px 5px rgba(0, 0, 0, 0.1); /* 调整阴影效果，仅保留上下 */

  .up-button {
    width: 20px;
    height: 20px;
    border: 1px solid #ccc;
    border-radius: 50%;
  }

  .name-edit-box {
    width: 100%;
  }
}

td {
  vertical-align: top;
}
</style>